<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\learn;

use app\common\model\learn\ArticleCategory as BookModel;

/**
 * 书籍分类模型
 * Class Category
 * @package app\store\model
 */
class ArticleCategory extends BookModel {

	
    /**
     * 获取列表记录
     * @param array $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $param = []): array
    {
        $list = $this->getAll($param);
        return $this->getTreeData($list);
    }

    /**
     * 获取所有记录
     * @param array $param
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getAll(array $param = []): \think\Collection
    {
        // 默认查询参数
        $params = $this->setQueryDefaultValue($param, [
            'status' => -1  // 状态(1显示 0隐藏 -1全部)
        ]);
        // 设置检索条件
        $filter = [];
        $params['status'] > -1 && $filter[] = ['status', '=', $params['status']];
        // 查询列表数据
        return $this->with(['image'])
            ->where($filter)
            ->order(['sort', 'create_time'])
            ->select();
    }

    /**
     * 获取树状列表
     * @param $list
     * @param int $parentId
     * @return array
     */
    private function getTreeData($list, int $parentId = 0): array
    {
        $data = [];
        foreach ($list as $key => $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->getTreeData($list, $item['category_id']);
                !empty($children) && $item['children'] = $children;
                $data[] = $item;
                unset($list[$key]);
            }
        }
        return $data;
    }

    /**
     * 过滤不存在的分类ID集
     * @param array $categoryIds
     * @param int|null $storeId
     * @return array
     */
    public static function filterCategoryIds(array $categoryIds, int $storeId = null): array
    {
        return (new static)->where('category_id', 'in', $categoryIds)
            ->where('store_id', '=', $storeId ?: self::$storeId)
            ->column('category_id');
    }
	/**
	 * 添加新记录
	 * @param $data
	 * @return bool
	 */
	public function add($data): bool {
		$data['store_id'] = self::$storeId;
		return $this->save($data);
	}

	/**
	 * 编辑记录
	 * @param $data
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function edit($data): bool {
		// 判断上级分类是否为当前子级
		if ($data['parent_id'] > 0) {
			// 获取所有上级id集
			$parentIds = $this->getTopCategoryIds($data['parent_id']);
			if (in_array($this['category_id'], $parentIds)) {
				$this->error = '上级分类不允许设置为当前子分类';
				return false;
			}
		}
		// 是否删除图片
		!isset($data['image_id']) && $data['image_id'] = 0;
		return $this->save($data) !== false;
	}

	/**
	 * 获取所有上级id集
	 * @param int $categoryId
	 * @param iterable|null $list
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	private function getTopCategoryIds(int $categoryId, iterable $list = null): array {
		static $parentIds = [];
		is_null($list) && $list = $this->getAll();
		foreach ($list as $item) {
			if ($item['category_id'] == $categoryId && $item['parent_id'] > 0) {
				$parentIds[] = $item['parent_id'];
				$this->getTopCategoryIds($item['parent_id'], $list);
			}
		}
		return $parentIds;
	}

	/**
	 * 删除记录
	 * @return bool
	 */
	public function remove(): bool {
		// 判断是否存在下级分类
		if (static::detail(['parent_id' => $this['category_id']])) {
			$this->error = '当前分类下存在子分类，不允许删除';
			return false;
		}
		// 判断该分类是否被商品引用
		$goodsCount = GoodsCategoryRel::getCountByCategoryId($this['category_id']);
		if ($goodsCount > 0) {
			$this->error = "该分类被{$goodsCount}个题目引用，不允许删除";
			return false;
		}
		// 删除分类记录
		return $this->delete();
	}
}
